<?php
class ModelArticleArticle extends Model {

	public function getArticles($filter = null) {
		$sql = "SELECT * FROM @@article WHERE 1";
		if ($filter) {
			if ($filter->get('category_id')) {
				$sql .= " AND category_id = " . (int) $filter->get('category_id');
			}
			$sql .= $filter->sort('article_id', 'DESC');
			$sql .= $filter->limit();
		}

		$query = $this->db->query($sql);
		return $query->rows;
	}

	public function getArticle($article_id) {
		return $this->db->queryOne("SELECT a.*, ac.content, c.name as category FROM @@article a LEFT JOIN @@article_content ac
				ON a.article_id = ac.article_id LEFT JOIN @@article_category c ON a.category_id=c.category_id WHERE a.article_id = $article_id");
	}

	public function updateHitsOne($article_id) {
		return $this->db->runSql("UPDATE @@article SET hits = hits + 1 WHERE article_id = {$article_id}");
	}
	
	public function getTotalArticles($filter = null) {
		$sql = "SELECT COUNT(*) AS total FROM @@article WHERE 1";
		if ($filter) {
			if ($filter->get('category_id')) {
				$sql .= " AND category_id = " . (int) $filter->get('category_id');
			}
		}
		return $this->db->queryOne($sql);
	}

	public function getCategory($category_id) {
		return $this->db->queryOne("SELECT * FROM @@article_category WHERE category_id = $category_id");
	}
	
	public function getCategories() {
		$query = $this->db->query("SELECT category_id, name FROM @@article_category ORDER BY sort_order");
		return $query->rows;
	}
}